import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import { Menu} from 'antd';
import * as actionCreators from './store/actionCreators';
import menuList from '../../config/menuConfig';
import './index.scss';

const SubMenu = Menu.SubMenu;

class LeftNav extends Component {

  constructor(props) {
    super(props);
    this.renderMenuList = this.renderMenuList.bind(this);
  }

  render() {
    const { menuList, loginStatus } = this.props;
    if(loginStatus){
      return (
        <div className='left-nav-wrapper'>
          <div className='logo'>
            <img src='/assets/images/logo-ant.svg' alt='' />
            <h1>MT 博客后台</h1>
          </div>
          <Menu
            defaultSelectedKeys={['/home']}
            theme='dark'
          >
            {menuList}
          </Menu>
        </div>
      );
    } else {
      return <Redirect to='/login' />
    }
  }

  componentWillMount = () => {
    const menuListDom = this.renderMenuList(menuList);
    this.props.initMenuList(menuListDom);
  }

  //渲染菜单列表
  renderMenuList(menuListData) {
    return menuListData.map((item) => {
      if(item.children) {
        return (
          <SubMenu key={item.key} title={item.title}>
            { this.renderMenuList(item.children) }
          </SubMenu>
        );
      }
      return (
        <Menu.Item key={item.key}>
          <NavLink to={item.key}>
            {item.title}
          </NavLink>
        </Menu.Item>
      );
    });
  }

}

const mapState = (state) => ({
  menuList: state.getIn(['leftNav', 'menuList']),
  loginStatus: state.getIn(['login', 'loginStatus'])
});

const mapDispatch = (dispatch) => ({
  initMenuList(menuListDom){
    dispatch(actionCreators.initMenu(menuListDom));
  }
});

export default connect(mapState, mapDispatch)(LeftNav);